<?php

/**
 * Identifies translations disputes
 *
 * @package BABEL
 * @since   BABEL 0.1.0
 * @version $Id: manage_languages.php 766 2008-05-14 08:52:59Z bjori $
 * @copyright Copyright (C) 2008 Anders Bjørnstad
 * @copyright Copyright (C) 2008 Frank Bølviken
 * @copyright Copyright (C) 2008 Magnus Bakke
 * @author  Anders Bjørnstad
 * @author  Frank Bølviken
 * @author 	Magnus Bakke
 * @license LGPL
 **/


/*
 * Inserts empty translations of every constant, with the new langcode.
 *
 * $langid 	int 	The language id
 */
function insertSingleLangConstants($langid) {
	$db = PDODB::connect();

	// Getting all the constant values from babel_values
	$DB_Q = "
	SELECT
		value_id
	FROM
		babel_values";

	if (!$db->runQuery($DB_Q, null, $result)) {
		throw new Exception("Query failed");
	}

	$stmt = $db->prepare("
						INSERT INTO
							babel_translations (
								revision, 
								translated_string, 
								status, 
								created,               
								language_id, 
								value_id, 
								changed_date
							) VALUES (
								0,        
								'',                
								?,
								'1970-01-01 00:00:00', 
								?,           
								?,        
								'1970-01-01 00:00:00'
								)
						 ");
	/*
	 * Loops through the array, and inserts them to the DB.
	 */
	foreach($result as $row) {
		$stmt->execute(array(BABEL_TRANSLATION_TRANSLATION, $langid, $row["value_id"]));
	}
}

/*
 * Prints the error page to screen.
 *
 * $logmsg 	String 	The message to be printed in the log
 * $usermsg String 	The message to be printed to the screen
 * $obj_tpl object 	The template object
 */
function print_error_exit($logmsg, $usermsg, $obj_tpl) {
	$obj_tpl->setFile("error", "babel/errorpage.html");
	$obj_tpl->setVar("VAR_SERIOUS_ERROR", $usermsg);
	$obj_tpl->pparse("error", "error");

	include('includes/babel/append.php');
	exit(1);
}

$action = isset($_GET["action"]) ? $_GET["action"] : "start";

/*
 * Checks if the user has pushed submit, and that it is infact a user logged in.
 */
if(isset($_POST["lang_changes"]) && isset($_SESSION['user'])) {

	// SQL statement which returns all the language codes in the DB
	$DB_QUERY = "
	SELECT 
		langcode
	FROM 
		babel_languages";
	
	if (!PDODB::runQuery($DB_QUERY, null, $stmt)) {
		throw new Exception("There was something wrong with the DB connection.. please contact administrator<br />Current action was aborted");
	}

	// Checking if we recived none rows
	if (($rowCount = $stmt->rowCount()) == 0) {
		// FIXME: Fix error handling
		$obj_tpl->setBlock("manage_status", "NO_LANG", "no_lang_ref");
		$obj_tpl->pparse("no_lang_ref", "manage_status", true);
		$error = "There are no languages available. Contact the administrator, if you think its an error<br />Current action was aborted";
	}

	// If everything is ok we proceed 
	else {
		foreach($stmt as $row) {
			
			// Getting the langcode for the checked field
			$langcode = $row["langcode"];
			$status = (int)$_POST[$langcode];

			// Check the Checked value with the selected value, and update the 
			// DB if it isnt.
			if(isset($_SESSION['user'][$row["langcode"]])) {
				if($_SESSION['user'][$row["langcode"]] != $status) {
					
					// SQL statement which updates the status of a given 
					// language. 
					$DB_Q = "
					UPDATE
						babel_languages
					SET
						status = ?
					WHERE
						langcode = ?";
					
					PDODB::execQuery($DB_Q, array($status, $langcode));
					$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("success", "Status successfully updated"));
					
				} else {
				}
			}
		}
	}
}

/*
 * Four different states of the manage_languages page.
 *
 * Start ("start") 										:	First page, listing up all the alternatives.
 * Add new language ("add") 							: 	Add a new language
 * Edit a language ("edit") 							:	Edit a existing language
 * Change/View status of all the languages ("status") 	: 	View and change the 
 *  														status of all the languages
 */
switch($action) {

/*
 * $action = "start"
 *
 * Lists all the alternatives for the user
 */
case "start":
	
	$obj_tpl->setFile("manage_list", "babel/manage_list.html");
	$obj_tpl->pparse("mange_list", "manage_list", true);
	break;
/*
 * $action = "add"
 *
 * Add a new language to the DB
 */	
case "add":
	$obj_tpl->setFile("manage_add", "babel/manage_add.html");
	
	if(isset($_POST["new_langcode"]) && $_POST["code"] != null && is_string($_POST["code"]) && $_POST["name"] != null && is_string($_POST["name"])){
		
		$lang_code = $_POST["code"];
		$lang_name = $_POST["name"];
		$lc = "empty";
		
		$DB_Q =
		   	"SELECT
		   		langcode
		   	FROM
		   		babel_languages
		   	WHERE
		   		langcode = ?";
		
		if(!PDODB::runQuery($DB_Q, array($lang_code), $stmt)) {
			throw new Exception("Select language code query failed!");
		}
		foreach($stmt as $row) {
			$lc = $row["langcode"];
		}

		//if the language code didden't exist in the db from before
		if($lang_code != $lc) {

			//Can't add languages with langcode longer then $max_code_length
			if(strlen($_POST["code"]) <= BABEL_LANGUAGE_CODE_LENGTH) {
			   	
			 /*
			 * SQL statement which inserts a new language to the DB
			 *
			 * 3 params:
			 * $lang_code 						: 	The language code
			 * $lang_name 						: 	The language name
			 * BABEL_TRANSLATION_TRANSLATION 	: 	Constant that defines 
			 * 										translation stage
			 */
			 
			   	$DB_QUERY = 
			   	"INSERT INTO 
			   		babel_languages(
			   		langcode, 
			   		name, 
			   		status,
			   		created, 
			   		changed_date) 
			   	VALUES (
				   	?,
				   	?,
				   	?,
				   	NOW(),
				   	NOW())";
				
				if (!PDODB::execquery($DB_QUERY, array($lang_code, $lang_name, BABEL_TRANSLATION_TRANSLATION), $langid)) {
					throw new Exception("Insert new language query failed");
				}
				insertSingleLangConstants($langid);
			
				$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("success", "New language added successfully."));
			}
			else {
				$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "No language created! Language code longer than " . BABEL_LANGUAGE_CODE_LENGTH . " not supported."));
			}
		}
		else {
			$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "No language created! There is already an existing language in the database with the same language code."));
		}	
	}
	
	$obj_tpl->pparse("manage_add", "manage_add", true);
	break;

/*
 * $action = "edit"
 *
 * Edit a chosen language
 */	
case "edit":
	$page = 0;
	$obj_tpl->setFile("manage_edit", "babel/manage_edit.html");
	
	/*
	 * Checks if status is "edit_lang"
	 *
	 * Prints out the template, with some information of the selected language
	 */
	if(isset($_POST["edit_lang"])){
		$page = 1;
		
		$obj_tpl->setFile("manage_edit_change", "babel/manage_edit_change.html");
		
		$langid = $_POST["lang_list"];
		$_SESSION["langid"] = $langid;
	
		/*
		 * SQL statement which returns a language.
		 * 
		 * 1 param:
		 * $langid 	: 	The language id
		 */
		$DB_QUERY = "
		SELECT 
			langcode,
			name
		FROM
			babel_languages
		WHERE
			language_id = ?";
		
		
		if(!PDODB::runQuery($DB_QUERY, array($langid), $stmt )) {
			throw new Exception("Query failed!");
								   
		}

		/*
		 * Loop through the result, and print it in the template
		 */
		foreach($stmt as $row) {
			$obj_tpl->setVar(array(
									"VAR_ORG_NAME"			=> $row["name"],
									"VAR_ORG_CODE"			=> $row["langcode"],
									$_SESSION["org_code"] 	=  $row["langcode"]
								  )
							);
			$obj_tpl->parse("manage_edit_change", "manage_edit_change");
		}
		
		$obj_tpl->pparse("manage_edit_change", "manage_edit_change", true);
		break;
	}

    /*
	 * Checks of the status is "change_lang" (submit button is pushed)
	 */	
	
	if(isset($_POST["change_lang"])) {
		$obj_tpl->setFile("manage_edit_change", "babel/manage_edit_change.html");
		$obj_tpl->setVar("LANG_NAME", $_POST["name"]);
		$page = 2;
		$langid = $_SESSION["langid"];
		$langcode_new = $_POST["code"];
		$langname_new = $_POST["name"];
		
		//checking if code is set and string
		if(isset($_POST["code"]) && is_string($_POST["code"])) {
			//Can't add languages with langcode longer then $max_code_length
			if(strlen($_POST["code"]) <= BABEL_LANGUAGE_CODE_LENGTH) {
				
				$lc = "empty";
				
				$DB_Q =
			   	"SELECT
			   		langcode
			   	FROM
			   		babel_languages
			   	WHERE
			   		langcode = ?";
			
				if(!PDODB::runQuery($DB_Q, array($langcode_new), $stmt)) {
					throw new Exception("Select language code query failed!");
				}
				foreach($stmt as $row) {
					$lc = $row["langcode"];
				}
		
				//If the language code didden't exist in the db from before or was the same
				if($langcode_new != $lc || $langcode_new == $_SESSION["org_code"]) {
					
					//Checking if name is set and is string
					if($_POST["name"] != null && is_string($_POST["name"])){

						/*
						 * SQL statement which updates a chosen language with user input
						 *
						 * 3 params:
						 * $langname_new 	: 	The new language name
						 * $langcode_new 	: 	The new language code
						 * $langid			: 	The language ID of the language to be updated
						 */
						
						$DB_QUERY = "
						UPDATE 
							babel_languages 
					  	SET
					   		name = ?,
					   		langcode = ?
					   	WHERE
					   		language_id = ?";
									
						if (!PDODB::execQuery($DB_QUERY, array($langname_new, $langcode_new, $langid))) {
							throw new Exception("Update query when editing language failed");
						}
												
						$obj_tpl->setFile("manage_list", "babel/manage_list.html");
						
						$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("success", "Successfully updated language."));
						
						if($page == 2) {
							$obj_tpl->pparse("mange_list", "manage_list", true);
							break;
						}
						
					}
					else {
						$obj_tpl->setFile("manage_list", "babel/manage_list.html");
						$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "You need to fill inn a language name."));
						
						if($page == 2) {
							$obj_tpl->pparse("mange_list", "manage_list", true);
							break;
						}
					}
				}
				else {
					$obj_tpl->setFile("manage_list", "babel/manage_list.html");
					$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "The language code you entered is already in use."));
					
					if($page == 2) {
						$obj_tpl->pparse("mange_list", "manage_list", true);
						break;
					}
				}
			}
			else {
				$obj_tpl->setFile("manage_list", "babel/manage_list.html");
				$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "No language created! Language code longer than " . BABEL_LANGUAGE_CODE_LENGTH . " not supported. Please retry."));
				
				if($page == 2) {
					$obj_tpl->pparse("mange_list", "manage_list", true);
					break;
				}
			}
		}
		else {
			$obj_tpl->setFile("manage_list", "babel/manage_list.html");
			$obj_tpl->setVar("VAR_TASK_SUBMITTED", $obj_html->displayMessage("error", "You need to fill inn a language code."));
			
			if($page == 2) {
				$obj_tpl->pparse("mange_list", "manage_list", true);
				break;
			}
		}
		$obj_tpl->pparse("manage_edit_change", "manage_edit_change", true);
		break;
	}
	
	$obj_tpl->setBlock("manage_edit", "list_lang", "list_lang_ref");
		
	/*
	 * SQL statement which returns the language info from the database
	 */
	$DB_QUERY = "
		SELECT 
			language_id, langcode, name
		FROM
			babel_languages";
		
		if (!PDODB::runQuery($DB_QUERY, null, $stmt)) {
			throw new Exception("Select query to fill dropdown box failed");
		}
		/*
		 * Loops through the array, and prints it out in the template
		 */
		foreach ($stmt as $row) {
			$obj_tpl->setVar(array(
								   "LANG_ID"		=> $row["language_id"],
								   "TXT_LANGUAGE" 	=> $row["name"]
								   )
							 );
			$obj_tpl->parse("list_lang_ref", "list_lang", true);
		}
		
	if($page == 0) {
		$obj_tpl->pparse("manage_edit", "manage_edit", true);
		break;
	}
	
/*
 * $action = "status"
 *
 * View and change the status of the languages
 */
case "status":
	$obj_tpl->setFile("manage_status", "babel/manage_status.html");
	$obj_tpl->setBlock("manage_status", "list", "list_ref");
	
	// SQL statement which returns the languages from the DB
	$DB_QUERY = "
	SELECT 
		langcode, name, status 
	FROM 
		babel_languages";
	
	if (!PDODB::runQuery($DB_QUERY, null, $stmt)) {
		throw new Exception("There was something wrong with the DB connection.. please contact administrator<br />Current action was aborted");
	}
	// Checking if we recived none rows
	if (($rowCount = $stmt->rowCount()) == 0) {
		$obj_tpl->setBlock("manage_status", "NO_LANG", "no_lang_ref");
		$obj_tpl->pparse("no_lang_ref", "manage_status", true);
		$error = "There are no languages available. Contact the administrator, if you think its an error<br />Current action was aborted";
	}
	else {
		/*
		 * Loops through the array, and prints out the languages on the template
		 */
		foreach($stmt as $row) {
			$checks = array(
						"VAR_TRANSLATION_CHECKED" => "",
						"VAR_DEP_CHECKED" => "",
						"VAR_LIVE_CHECKED" => "",
						"VAR_FINAL_CHECKED" => "",
					);
			/*
			 * Finds out what status the languages have.
			 */
			switch($row["status"]) {
				case BABEL_TRANSLATION_DEPRICATED:
					$checks["VAR_DEP_CHECKED"] = "checked";
					break;
				case BABEL_TRANSLATION_TRANSLATION:
					$checks["VAR_TRANSLATION_CHECKED"] = "checked";
					break;
				case BABEL_TRANSLATION_LIVE:
					$checks["VAR_LIVE_CHECKED"] = "checked";
					break;
				case BABEL_TRANSLATION_FINAL:
					$checks["VAR_FINAL_CHECKED"] = "checked";
					break;
			}
			
			//Setting the values from above into a session variable
			$_SESSION['user'][$row["langcode"]] = $row["status"];

			$arr = array(
				"ROW_TR_BGCOLOR" 		=> $rowCount % 2 ? '#EEEEEE' : '#DDDDDD',
				"VAR_LANGUAGE_CODE" 	=> $row["langcode"],
				"VAR_LANGUAGE_NAME" 	=> $row["name"],
			);
			$checks = array_merge($checks, $arr);
			
			$rowCount++;
			
			$obj_tpl->setVar($checks);
			$obj_tpl->parse("list_ref", "list", true);
		}
	}

	$obj_tpl->pparse("manage_status", "manage_status", true);
	break;
}
